package servlet;

import entity.Animal;
import entity.AnimalCategory;
import service.AnimalCategoryService;
import service.AnimalService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/deleteAnimal")
public class DeleteAnimalServlet extends HttpServlet {
    private AnimalService animalService;

    private  AnimalCategoryService animalCategoryService ;
    @Override
    public void init() throws ServletException {
        super.init();
        animalCategoryService = new AnimalCategoryService();
        animalService = new AnimalService(); // 初始化 AnimalService
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取动物ID
        String animalIdStr = request.getParameter("id");
        if (animalIdStr == null || animalIdStr.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "动物ID不能为空");
            return;
        }

        int animalId;
        try {
            animalId = Integer.parseInt(animalIdStr);
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "动物ID格式错误");
            return;
        }

        // 调用 Service 层删除动物
        boolean result = animalService.deleteAnimal(animalId);

        // 根据删除结果进行处理
        if (result) {
            // 查询所有动物分类
            List<AnimalCategory> categories = animalCategoryService.getAllAnimalCategories();
            request.setAttribute("categories", categories);
            // 删除成功，重定向回动物管理页面
            List<Animal> animals = animalService.getAllAnimals();
            request.setAttribute("animals", animals);
            request.getRequestDispatcher("adminIndex.jsp").forward(request, response);
        } else {
            // 删除失败，返回错误信息
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "删除动物失败");
        }
    }
}
